/**
 * 番茄时钟主应用逻辑
 * 整合计时器、音频管理和用户界面
 */

class PomodoroApp {
    constructor() {
        // 初始化核心组件
        this.timer = new PomodoroTimer();
        this.audioManager = new AudioManager();
        this.focusMode = new FocusMode();
        this.themeManager = new ThemeManager();
        this.settingsManager = new SettingsManager();
        this.statisticsManager = new StatisticsManager();
        this.taskManager = new TaskManager();
        
        // DOM元素引用
        this.elements = {};
        
        // 应用状态
        this.isInitialized = false;
        
        console.log('PomodoroApp constructor called');
    }
    
    /**
     * 初始化应用
     */
    init() {
        console.log('Initializing PomodoroApp...');
        
        // 获取DOM元素
        this.initElements();
        
        // 设置事件监听器
        this.setupEventListeners();
        
        // 设置计时器回调
        this.setupTimerCallbacks();
        
        // 初始化界面
        this.updateUI();
        
        // 初始化主题设置
        this.initThemeSettings();
        
        // 请求音频权限
        this.requestAudioPermission();
        
        this.isInitialized = true;
        console.log('PomodoroApp initialized successfully');
    }
    
    /**
     * 获取DOM元素引用
     */
    initElements() {
        this.elements = {
            // 容器
            container: document.querySelector('.container'),
            
            // 状态显示
            currentStatus: document.getElementById('currentStatus'),
            tomatoCount: document.getElementById('tomatoCount'),
            
            // 时间显示
            timeDisplay: document.getElementById('timeDisplay'),
            progressCircle: document.getElementById('progressCircle'),
            
            // 控制按钮
            startBtn: document.getElementById('startBtn'),
            pauseBtn: document.getElementById('pauseBtn'),
            resetBtn: document.getElementById('resetBtn'),
            focusBtn: document.getElementById('focusBtn'),
            settingsBtn: document.getElementById('settingsBtn'),
            
            // 状态指示器
            workIndicator: document.getElementById('workIndicator'),
            breakIndicator: document.getElementById('breakIndicator'),
            longBreakIndicator: document.getElementById('longBreakIndicator'),
            
            // 番茄进度点
            tomatoDots: [
                document.getElementById('tomato1'),
                document.getElementById('tomato2'),
                document.getElementById('tomato3'),
                document.getElementById('tomato4')
            ],
            
            // 设置弹窗相关
            settingsModal: document.getElementById('settingsModal'),
            closeSettingsBtn: document.getElementById('closeSettingsBtn'),
            cancelSettingsBtn: document.getElementById('cancelSettingsBtn'),
            confirmSettingsBtn: document.getElementById('confirmSettingsBtn'),
            
            // 时间设置控件
            workHours: document.getElementById('workHours'),
            workMinutes: document.getElementById('workMinutes'),
            workSeconds: document.getElementById('workSeconds'),
            
            shortBreakHours: document.getElementById('shortBreakHours'),
            shortBreakMinutes: document.getElementById('shortBreakMinutes'),
            shortBreakSeconds: document.getElementById('shortBreakSeconds'),
            
            longBreakHours: document.getElementById('longBreakHours'),
            longBreakMinutes: document.getElementById('longBreakMinutes'),
            longBreakSeconds: document.getElementById('longBreakSeconds'),
            
            // 开关控件
            enableShortBreak: document.getElementById('enableShortBreak'),
            enableLongBreak: document.getElementById('enableLongBreak'),
            longBreakCycle: document.getElementById('longBreakCycle'),
            
            // 时间选择器容器
            shortBreakPicker: document.getElementById('shortBreakPicker'),
            longBreakPicker: document.getElementById('longBreakPicker'),
            
            // 音频设置相关
            enableAudio: document.getElementById('enableAudio'),
            audioSettings: document.getElementById('audioSettings'),
            soundTypeSelect: document.getElementById('soundTypeSelect'),
            previewSoundBtn: document.getElementById('previewSoundBtn'),
            volumeSlider: document.getElementById('volumeSlider'),
            volumeValue: document.getElementById('volumeValue'),
            
            // 主题设置相关
            themeOptions: document.querySelectorAll('.theme-option'),
            fontSizeRadios: document.querySelectorAll('input[name="fontSize"]'),
            darkModeToggle: document.getElementById('darkModeToggle'),
            progressStyleRadios: document.querySelectorAll('input[name="progressStyle"]'),
            
            // 通知设置相关
            enableDesktopNotifications: document.getElementById('enableDesktopNotifications'),
            enableCustomNotifications: document.getElementById('enableCustomNotifications'),
            customNotificationContent: document.getElementById('customNotificationContent'),
            customNotificationTitle: document.getElementById('customNotificationTitle'),
            customWorkCompleteText: document.getElementById('customWorkCompleteText'),
            customShortBreakCompleteText: document.getElementById('customShortBreakCompleteText'),
            customLongBreakCompleteText: document.getElementById('customLongBreakCompleteText'),
            notificationRequireInteraction: document.getElementById('notificationRequireInteraction'),
            notificationAutoCloseTime: document.getElementById('notificationAutoCloseTime'),
            
            // 数据管理相关
            exportSettingsBtn: document.getElementById('exportSettingsBtn'),
            importSettingsBtn: document.getElementById('importSettingsBtn'),
            importFileInput: document.getElementById('importFileInput'),
            resetSettingsBtn: document.getElementById('resetSettingsBtn'),
            clearDataBtn: document.getElementById('clearDataBtn'),
            settingsSize: document.getElementById('settingsSize'),
            totalUsed: document.getElementById('totalUsed'),
            
            // 统计面板相关
            statsBtn: document.getElementById('statsBtn'),
            statisticsModal: document.getElementById('statisticsModal'),
            closeStatsBtn: document.getElementById('closeStatsBtn'),
            
            // 统计数据显示
            todayPomodoros: document.getElementById('todayPomodoros'),
            todayFocusTime: document.getElementById('todayFocusTime'),
            weekPomodoros: document.getElementById('weekPomodoros'),
            weekFocusTime: document.getElementById('weekFocusTime'),
            totalPomodoros: document.getElementById('totalPomodoros'),
            totalFocusTime: document.getElementById('totalFocusTime'),
            streakDays: document.getElementById('streakDays'),
            
            // 图表控制
            trendChart7Btn: document.getElementById('trendChart7Btn'),
            trendChart30Btn: document.getElementById('trendChart30Btn'),
            
            // 效率分析
            avgDailyPomodoros: document.getElementById('avgDailyPomodoros'),
            peakHour: document.getElementById('peakHour'),
            focusConsistency: document.getElementById('focusConsistency'),
            trendStatus: document.getElementById('trendStatus'),
            
            // 数据管理按钮
            exportStatsBtn: document.getElementById('exportStatsBtn'),
            resetStatsBtn: document.getElementById('resetStatsBtn'),
            
            // 任务管理相关
            tasksBtn: document.getElementById('tasksBtn'),
            tasksModal: document.getElementById('tasksModal'),
            closeTasksBtn: document.getElementById('closeTasksBtn'),
            
            // 任务输入
            taskInput: document.getElementById('taskInput'),
            addTaskBtn: document.getElementById('addTaskBtn'),
            
            // 任务列表
            tasksList: document.getElementById('tasksList'),
            
            // 任务筛选
            filterAllBtn: document.getElementById('filterAllBtn'),
            filterActiveBtn: document.getElementById('filterActiveBtn'),
            filterCompletedBtn: document.getElementById('filterCompletedBtn'),
            
            // 任务统计
            totalTasksCount: document.getElementById('totalTasksCount'),
            completedTasksCount: document.getElementById('completedTasksCount'),
            completionRate: document.getElementById('completionRate'),
            
            // 任务管理按钮
            clearCompletedBtn: document.getElementById('clearCompletedBtn')
        };
        
        // 检查必要元素是否存在
        const requiredElements = ['currentStatus', 'timeDisplay', 'startBtn', 'pauseBtn', 'resetBtn'];
        for (const elementId of requiredElements) {
            if (!this.elements[elementId]) {
                console.error(`Required element not found: ${elementId}`);
            }
        }
    }
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 开始按钮
        if (this.elements.startBtn) {
            this.elements.startBtn.addEventListener('click', () => {
                this.handleStart();
            });
        }
        
        // 暂停按钮
        if (this.elements.pauseBtn) {
            this.elements.pauseBtn.addEventListener('click', () => {
                this.handlePause();
            });
        }
        
        // 重置按钮
        if (this.elements.resetBtn) {
            this.elements.resetBtn.addEventListener('click', () => {
                this.handleReset();
            });
        }
        
        // 专注模式按钮
        if (this.elements.focusBtn) {
            this.elements.focusBtn.addEventListener('click', () => {
                this.handleFocusMode();
            });
        }
        
        // 设置按钮
        if (this.elements.settingsBtn) {
            this.elements.settingsBtn.addEventListener('click', () => {
                this.openSettings();
            });
        }
        
        // 设置弹窗关闭按钮
        if (this.elements.closeSettingsBtn) {
            this.elements.closeSettingsBtn.addEventListener('click', () => {
                this.closeSettings();
            });
        }
        
        // 设置弹窗取消按钮
        if (this.elements.cancelSettingsBtn) {
            this.elements.cancelSettingsBtn.addEventListener('click', () => {
                this.closeSettings();
            });
        }
        
        // 设置弹窗确认按钮
        if (this.elements.confirmSettingsBtn) {
            this.elements.confirmSettingsBtn.addEventListener('click', () => {
                this.saveSettings();
            });
        }
        
        // 短休息开关
        if (this.elements.enableShortBreak) {
            this.elements.enableShortBreak.addEventListener('change', () => {
                this.toggleShortBreakPicker();
            });
        }
        
        // 长休息开关
        if (this.elements.enableLongBreak) {
            this.elements.enableLongBreak.addEventListener('change', () => {
                this.toggleLongBreakPicker();
            });
        }
        
        // 音频设置事件监听器
        this.setupAudioEventListeners();
        
        // 主题设置事件监听器
        this.setupThemeEventListeners();
        
        // 数据管理事件监听器
        this.setupDataManagementEventListeners();
        
        // 通知设置事件监听器
        this.setupNotificationEventListeners();
        
        // 统计面板事件监听器
        this.setupStatisticsEventListeners();
        
        // 任务管理事件监听器
        this.setupTasksEventListeners();
        
        // 点击弹窗背景关闭
        if (this.elements.settingsModal) {
            this.elements.settingsModal.addEventListener('click', (event) => {
                if (event.target === this.elements.settingsModal) {
                    this.closeSettings();
                }
            });
        }
        
        // 统计弹窗背景关闭
        if (this.elements.statisticsModal) {
            this.elements.statisticsModal.addEventListener('click', (event) => {
                if (event.target === this.elements.statisticsModal) {
                    this.closeStatistics();
                }
            });
        }
        
        // 任务弹窗背景关闭
        if (this.elements.tasksModal) {
            this.elements.tasksModal.addEventListener('click', (event) => {
                if (event.target === this.elements.tasksModal) {
                    this.closeTasks();
                }
            });
        }
        
        // 键盘快捷键
        document.addEventListener('keydown', (event) => {
            this.handleKeyboard(event);
        });
        
        // 页面可见性变化
        document.addEventListener('visibilitychange', () => {
            this.handleVisibilityChange();
        });
        
        // 页面卸载前保存状态
        window.addEventListener('beforeunload', () => {
            this.saveState();
        });
        
        console.log('Event listeners setup complete');
    }
    
    /**
     * 设置计时器回调函数
     */
    setupTimerCallbacks() {
        this.timer.setCallbacks({
            onTick: (data) => {
                this.handleTick(data);
            },
            onStateChange: (data) => {
                this.handleStateChange(data);
            },
            onComplete: (data) => {
                this.handleComplete(data);
            }
        });
    }
    
    /**
     * 处理开始按钮点击
     */
    handleStart() {
        console.log('Start button clicked');
        this.timer.start();
        this.audioManager.requestPermission();
    }
    
    /**
     * 处理暂停按钮点击
     */
    handlePause() {
        console.log('Pause button clicked');
        this.timer.pause();
    }
    
    /**
     * 处理重置按钮点击
     */
    handleReset() {
        console.log('Reset button clicked');
        this.timer.reset();
        this.clearVisualEffects();
        
        // 退出专注模式
        if (this.focusMode.isInFocusMode()) {
            this.focusMode.exit();
        }
    }
    
    /**
     * 处理专注模式按钮点击
     */
    handleFocusMode() {
        console.log('Focus mode button clicked');
        
        if (this.focusMode.isInFocusMode()) {
            this.focusMode.exit();
        } else {
            // 如果计时器未运行，先开始计时
            if (!this.timer.isRunning) {
                this.timer.start();
            }
            this.focusMode.enter(this.timer);
        }
        
        this.updateFocusButton();
    }
    
    /**
     * 更新专注模式按钮状态
     */
    updateFocusButton() {
        if (this.elements.focusBtn) {
            const isInFocusMode = this.focusMode.isInFocusMode();
            this.elements.focusBtn.textContent = isInFocusMode ? '退出专注' : '专注模式';
            this.elements.focusBtn.classList.toggle('active', isInFocusMode);
        }
    }
    
    /**
     * 处理键盘事件
     */
    handleKeyboard(event) {
        // 防止在输入框中触发
        if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
            return;
        }
        
        switch (event.code) {
            case 'Space':
                event.preventDefault();
                if (this.timer.isRunning) {
                    this.handlePause();
                } else {
                    this.handleStart();
                }
                break;
            case 'KeyR':
                event.preventDefault();
                this.handleReset();
                break;
            case 'KeyF':
                event.preventDefault();
                this.handleFocusMode();
                break;
        }
    }
    
    /**
     * 处理页面可见性变化
     */
    handleVisibilityChange() {
        if (document.hidden) {
            console.log('Page hidden');
        } else {
            console.log('Page visible');
            // 页面重新可见时更新UI
            this.updateUI();
        }
    }
    
    /**
     * 处理计时器滴答
     */
    handleTick(data) {
        this.updateTimeDisplay(data.formattedTime);
        this.updateProgress(data.progress);
        
        // 更新专注模式显示
        if (this.focusMode.isInFocusMode()) {
            this.focusMode.updateFocusMode();
        }
    }
    
    /**
     * 处理状态变化
     */
    handleStateChange(data) {
        console.log('State changed:', data);
        
        this.updateStatusDisplay(data.stateText);
        this.updateTomatoCount(data.dailyPomodoros);
        this.updateControlButtons(data.isRunning, data.state);
        this.updateStateIndicators(data.state);
        this.updateTomatoProgress(data.currentCyclePomodoros);
        this.updateTheme(data.state);
    }
    
    /**
     * 处理计时完成
     */
    handleComplete(data) {
        console.log('Timer completed:', data);
        
        // 记录统计数据
        this.recordStatistics(data);
        
        // 记录任务进度（仅在工作时间完成时）
        if (data.completedState === 'work') {
            this.recordTaskPomodoro();
        }
        
        // 播放提示音
        this.playCompletionSound(data.completedState);
        
        // 显示视觉效果
        this.showCompletionEffect();
        
        // 显示通知
        this.showNotification(data.completedState);
    }
    
    /**
     * 更新时间显示
     */
    updateTimeDisplay(formattedTime) {
        if (this.elements.timeDisplay) {
            this.elements.timeDisplay.textContent = formattedTime;
        }
    }
    
    /**
     * 更新进度环
     */
    updateProgress(progress) {
        if (this.elements.progressCircle) {
            const circumference = 2 * Math.PI * 90; // r=90
            const offset = circumference - (progress / 100) * circumference;
            this.elements.progressCircle.style.strokeDashoffset = offset;
        }
    }
    
    /**
     * 更新状态显示
     */
    updateStatusDisplay(statusText) {
        if (this.elements.currentStatus) {
            this.elements.currentStatus.textContent = statusText;
        }
    }
    
    /**
     * 更新番茄计数
     */
    updateTomatoCount(count) {
        if (this.elements.tomatoCount) {
            this.elements.tomatoCount.textContent = count;
        }
    }
    
    /**
     * 更新控制按钮状态
     */
    updateControlButtons(isRunning, state) {
        if (this.elements.startBtn) {
            this.elements.startBtn.disabled = isRunning;
            this.elements.startBtn.textContent = state === 'paused' ? '继续' : '开始';
        }
        
        if (this.elements.pauseBtn) {
            this.elements.pauseBtn.disabled = !isRunning;
        }
    }
    
    /**
     * 更新状态指示器
     */
    updateStateIndicators(state) {
        // 清除所有活动状态
        [this.elements.workIndicator, this.elements.breakIndicator, this.elements.longBreakIndicator]
            .forEach(indicator => {
                if (indicator) {
                    indicator.classList.remove('active');
                }
            });
        
        // 设置当前活动状态
        switch (state) {
            case 'work':
                if (this.elements.workIndicator) {
                    this.elements.workIndicator.classList.add('active');
                }
                break;
            case 'short_break':
                if (this.elements.breakIndicator) {
                    this.elements.breakIndicator.classList.add('active');
                }
                break;
            case 'long_break':
                if (this.elements.longBreakIndicator) {
                    this.elements.longBreakIndicator.classList.add('active');
                }
                break;
        }
    }
    
    /**
     * 更新番茄进度点
     */
    updateTomatoProgress(currentCyclePomodoros) {
        this.elements.tomatoDots.forEach((dot, index) => {
            if (dot) {
                if (index < currentCyclePomodoros) {
                    dot.classList.add('completed');
                } else {
                    dot.classList.remove('completed');
                }
            }
        });
    }
    
    /**
     * 更新主题
     */
    updateTheme(state) {
        if (!this.elements.container) return;
        
        // 清除所有主题类
        this.elements.container.classList.remove('work-mode', 'break-mode', 'long-break-mode', 'paused');
        
        // 添加对应主题类
        switch (state) {
            case 'work':
                this.elements.container.classList.add('work-mode');
                break;
            case 'short_break':
                this.elements.container.classList.add('break-mode');
                break;
            case 'long_break':
                this.elements.container.classList.add('long-break-mode');
                break;
            case 'paused':
                this.elements.container.classList.add('paused');
                break;
        }
    }
    
    /**
     * 播放完成提示音
     */
    playCompletionSound(completedState) {
        const soundType = {
            'work': 'work_complete',
            'short_break': 'break_complete',
            'long_break': 'long_break_complete'
        }[completedState] || 'work_complete';
        
        this.audioManager.playNotification(soundType);
    }
    
    /**
     * 显示完成视觉效果
     */
    showCompletionEffect() {
        if (this.elements.container) {
            this.elements.container.classList.add('time-up');
            
            // 3秒后移除效果
            setTimeout(() => {
                this.clearVisualEffects();
            }, 3000);
        }
    }
    
    /**
     * 清除视觉效果
     */
    clearVisualEffects() {
        if (this.elements.container) {
            this.elements.container.classList.remove('time-up');
        }
    }
    
    /**
     * 显示浏览器通知
     */
    showNotification(completedState) {
        if ('Notification' in window && Notification.permission === 'granted') {
            const notificationSettings = this.getNotificationSettings();
            
            let message, title;
            if (notificationSettings.customText && notificationSettings.customMessages[completedState]) {
                message = notificationSettings.customMessages[completedState];
                title = notificationSettings.customTitle || '番茄时钟';
            } else {
                const messages = {
                    'work': '工作时间结束！该休息一下了 🎉',
                    'short_break': '短休息结束！继续加油工作 💪',
                    'long_break': '长休息结束！准备开始新的番茄周期 🍅'
                };
                message = messages[completedState] || '时间到！';
                title = '番茄时钟';
            }
            
            const notification = new Notification(title, {
                body: message,
                icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90">🍅</text></svg>',
                tag: 'pomodoro-timer',
                requireInteraction: notificationSettings.requireInteraction || false
            });
            
            // 通知点击交互
            notification.onclick = () => {
                window.focus();
                notification.close();
                
                // 根据完成的状态执行相应操作
                if (completedState === 'work') {
                    // 工作完成，可以选择开始休息
                    this.handleNotificationClick('work_completed');
                } else {
                    // 休息完成，可以选择开始工作
                    this.handleNotificationClick('break_completed');
                }
            };
            
            // 自动关闭通知
            setTimeout(() => {
                notification.close();
            }, notificationSettings.autoClose || 5000);
        }
    }
    
    /**
     * 获取通知设置
     */
    getNotificationSettings() {
        try {
            const stored = localStorage.getItem('pomodoro_notification_settings');
            if (stored) {
                return JSON.parse(stored);
            }
        } catch (error) {
            console.error('Error loading notification settings:', error);
        }
        
        // 默认通知设置
        return {
            enabled: true,
            customText: false,
            customTitle: '番茄时钟',
            customMessages: {
                work: '工作时间结束！该休息一下了 🎉',
                short_break: '短休息结束！继续加油工作 💪',
                long_break: '长休息结束！准备开始新的番茄周期 🍅'
            },
            requireInteraction: false,
            autoClose: 5000
        };
    }
    
    /**
     * 保存通知设置
     */
    saveNotificationSettings(settings) {
        try {
            localStorage.setItem('pomodoro_notification_settings', JSON.stringify(settings));
        } catch (error) {
            console.error('Error saving notification settings:', error);
        }
    }
    
    /**
     * 处理通知点击事件
     */
    handleNotificationClick(type) {
        console.log('Notification clicked:', type);
        
        switch (type) {
            case 'work_completed':
                // 工作完成，询问是否开始休息
                if (confirm('工作时间已完成！是否立即开始休息？')) {
                    this.timer.start();
                }
                break;
            case 'break_completed':
                // 休息完成，询问是否开始工作
                if (confirm('休息时间已完成！是否立即开始工作？')) {
                    this.timer.start();
                }
                break;
        }
    }
    
    /**
     * 显示通知权限引导
     */
    showNotificationPermissionGuide() {
        if ('Notification' in window && Notification.permission === 'default') {
            const guide = document.createElement('div');
            guide.className = 'notification-permission-guide';
            guide.innerHTML = `
                <div class="guide-content">
                    <div class="guide-icon">🔔</div>
                    <div class="guide-text">
                        <h4>开启桌面通知</h4>
                        <p>允许番茄时钟发送桌面通知，让您在专注工作时不错过任何提醒</p>
                    </div>
                    <div class="guide-actions">
                        <button class="guide-btn allow-btn" id="allowNotificationBtn">允许通知</button>
                        <button class="guide-btn dismiss-btn" id="dismissGuideBtn">暂不开启</button>
                    </div>
                </div>
            `;
            
            // 添加样式
            guide.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: white;
                border-radius: 12px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.15);
                padding: 20px;
                max-width: 320px;
                z-index: 10000;
                border-left: 4px solid #ff6b6b;
            `;
            
            document.body.appendChild(guide);
            
            // 事件监听
            document.getElementById('allowNotificationBtn').addEventListener('click', async () => {
                try {
                    const permission = await Notification.requestPermission();
                    if (permission === 'granted') {
                        this.showNotification('通知权限已开启！', 'success');
                    }
                } catch (error) {
                    console.error('Request notification permission error:', error);
                }
                guide.remove();
            });
            
            document.getElementById('dismissGuideBtn').addEventListener('click', () => {
                guide.remove();
            });
            
            // 5秒后自动隐藏
            setTimeout(() => {
                if (guide.parentNode) {
                    guide.remove();
                }
            }, 10000);
        }
    }
    
    /**
     * 请求音频和通知权限
     */
    async requestAudioPermission() {
        // 请求音频权限
        await this.audioManager.requestPermission();
        
        // 显示通知权限引导
        setTimeout(() => {
            this.showNotificationPermissionGuide();
        }, 2000);
    }
    
    /**
     * 更新整个UI
     */
    updateUI() {
        const status = this.timer.getStatus();
        this.handleStateChange(status);
        this.handleTick({
            formattedTime: status.formattedTime,
            progress: status.progress
        });
        this.updateFocusButton();
    }
    
    /**
     * 保存应用状态
     */
    saveState() {
        // 这里可以保存更多状态信息
        console.log('Saving app state...');
    }
    
    /**
     * 获取应用状态
     */
    getAppStatus() {
        return {
            timer: this.timer.getStatus(),
            audio: this.audioManager.getSettings(),
            isInitialized: this.isInitialized
        };
    }
    
    /**
     * 打开设置弹窗
     */
    openSettings() {
        console.log('Opening settings...');
        this.loadSettingsFromConfig();
        this.elements.settingsModal.classList.add('show');
        this.toggleShortBreakPicker();
        this.toggleLongBreakPicker();
    }
    
    /**
     * 关闭设置弹窗
     */
    closeSettings() {
        console.log('Closing settings...');
        this.elements.settingsModal.classList.remove('show');
    }
    
    /**
     * 从配置加载设置到界面
     */
    loadSettingsFromConfig() {
        const config = this.timer.getConfig();
        
        // 工作时间
        const workHours = Math.floor(config.workTime / 3600);
        const workMinutes = Math.floor((config.workTime % 3600) / 60);
        const workSeconds = config.workTime % 60;
        
        this.elements.workHours.value = workHours;
        this.elements.workMinutes.value = workMinutes;
        this.elements.workSeconds.value = workSeconds;
        
        // 短休息时间
        const shortBreakHours = Math.floor(config.shortBreak / 3600);
        const shortBreakMinutes = Math.floor((config.shortBreak % 3600) / 60);
        const shortBreakSeconds = config.shortBreak % 60;
        
        this.elements.shortBreakHours.value = shortBreakHours;
        this.elements.shortBreakMinutes.value = shortBreakMinutes;
        this.elements.shortBreakSeconds.value = shortBreakSeconds;
        
        // 长休息时间
        const longBreakHours = Math.floor(config.longBreak / 3600);
        const longBreakMinutes = Math.floor((config.longBreak % 3600) / 60);
        const longBreakSeconds = config.longBreak % 60;
        
        this.elements.longBreakHours.value = longBreakHours;
        this.elements.longBreakMinutes.value = longBreakMinutes;
        this.elements.longBreakSeconds.value = longBreakSeconds;
        
        // 开关状态
        this.elements.enableShortBreak.checked = config.enableShortBreak;
        this.elements.enableLongBreak.checked = config.enableLongBreak;
        this.elements.longBreakCycle.value = config.longBreakCycle;
        
        // 音频设置
        this.loadAudioSettingsFromConfig();
        
        // 主题设置
        this.loadThemeSettingsFromConfig();
    }
    
    /**
     * 保存设置
     */
    saveSettings() {
        console.log('Saving settings...');
        
        try {
            // 获取工作时间
            const workTime = parseInt(this.elements.workHours.value) * 3600 +
                           parseInt(this.elements.workMinutes.value) * 60 +
                           parseInt(this.elements.workSeconds.value);
            
            // 获取短休息时间
            const shortBreak = parseInt(this.elements.shortBreakHours.value) * 3600 +
                             parseInt(this.elements.shortBreakMinutes.value) * 60 +
                             parseInt(this.elements.shortBreakSeconds.value);
            
            // 获取长休息时间
            const longBreak = parseInt(this.elements.longBreakHours.value) * 3600 +
                            parseInt(this.elements.longBreakMinutes.value) * 60 +
                            parseInt(this.elements.longBreakSeconds.value);
            
            // 验证时间设置
            if (workTime < 60) {
                alert('工作时间不能少于1分钟');
                return;
            }
            
            if (this.elements.enableShortBreak.checked && shortBreak < 60) {
                alert('短休息时间不能少于1分钟');
                return;
            }
            
            if (this.elements.enableLongBreak.checked && longBreak < 60) {
                alert('长休息时间不能少于1分钟');
                return;
            }
            
            // 构建新配置
            const newConfig = {
                workTime: workTime,
                shortBreak: shortBreak,
                longBreak: longBreak,
                enableShortBreak: this.elements.enableShortBreak.checked,
                enableLongBreak: this.elements.enableLongBreak.checked,
                longBreakCycle: parseInt(this.elements.longBreakCycle.value)
            };
            
            // 更新计时器配置
            this.timer.updateConfig(newConfig);
            
            // 保存音频设置
            this.saveAudioSettings();
            
            // 保存主题设置
            this.saveThemeSettings();
            
            // 关闭设置弹窗
            this.closeSettings();
            
            // 强制刷新界面状态
            setTimeout(() => {
                this.updateUI();
                this.refreshUIState();
            }, 100);
            
            // 显示成功消息
            this.showNotification('设置已保存', 'success');
            
        } catch (error) {
            console.error('Error saving settings:', error);
            alert('保存设置时出错，请检查输入');
        }
    }
    
    /**
     * 刷新UI状态
     */
    refreshUIState() {
        try {
            // 重新应用主题
            if (this.themeManager) {
                this.themeManager.applyTheme();
            }
            
            // 更新进度环
            const status = this.timer.getStatus();
            this.updateProgress(status.progress);
            
            // 确保按钮状态正确
            this.updateControlButtons(status.isRunning, status.state);
            
            // 更新状态指示器
            this.updateStateIndicators(status.state);
            
        } catch (error) {
            console.error('Refresh UI state error:', error);
        }
    }
    
    /**
     * 切换短休息时间选择器状态
     */
    toggleShortBreakPicker() {
        const enabled = this.elements.enableShortBreak.checked;
        if (this.elements.shortBreakPicker) {
            if (enabled) {
                this.elements.shortBreakPicker.classList.remove('disabled');
            } else {
                this.elements.shortBreakPicker.classList.add('disabled');
            }
        }
    }
    
    /**
     * 切换长休息时间选择器状态
     */
    toggleLongBreakPicker() {
        const enabled = this.elements.enableLongBreak.checked;
        if (this.elements.longBreakPicker) {
            if (enabled) {
                this.elements.longBreakPicker.classList.remove('disabled');
            } else {
                this.elements.longBreakPicker.classList.add('disabled');
            }
        }
    }
    
    /**
     * 设置音频相关事件监听器
     */
    setupAudioEventListeners() {
        // 音频开关
        if (this.elements.enableAudio) {
            this.elements.enableAudio.addEventListener('change', () => {
                this.toggleAudioSettings();
                this.audioManager.setEnabled(this.elements.enableAudio.checked);
            });
        }
        
        // 音效类型选择
        if (this.elements.soundTypeSelect) {
            this.elements.soundTypeSelect.addEventListener('change', () => {
                const soundType = this.elements.soundTypeSelect.value;
                this.audioManager.setSoundType(soundType);
            });
        }
        
        // 预览按钮
        if (this.elements.previewSoundBtn) {
            this.elements.previewSoundBtn.addEventListener('click', () => {
                this.previewSound();
            });
        }
        
        // 音量滑块
        if (this.elements.volumeSlider) {
            this.elements.volumeSlider.addEventListener('input', () => {
                const volume = parseFloat(this.elements.volumeSlider.value);
                this.audioManager.setVolume(volume);
                this.updateVolumeDisplay(volume);
            });
        }
        
        // 初始化音频设置界面
        this.initAudioSettings();
    }
    
    /**
     * 初始化音频设置界面
     */
    initAudioSettings() {
        const audioSettings = this.audioManager.getSettings();

        // 设置音频开关状态
        if (this.elements.enableAudio) {
            this.elements.enableAudio.checked = audioSettings.isEnabled;
        }

        // 设置音效类型
        if (this.elements.soundTypeSelect) {
            this.elements.soundTypeSelect.value = audioSettings.soundType || 'bell';
        }

        // 设置音量
        if (this.elements.volumeSlider) {
            this.elements.volumeSlider.value = audioSettings.volume || 0.7;
            this.updateVolumeDisplay(audioSettings.volume || 0.7);
        }

        // 初始化音频设置区域状态
        this.toggleAudioSettings();
    }
    
    /**
     * 切换音频设置区域的启用/禁用状态
     */
    toggleAudioSettings() {
        const enabled = this.elements.enableAudio && this.elements.enableAudio.checked;
        if (this.elements.audioSettings) {
            if (enabled) {
                this.elements.audioSettings.classList.remove('disabled');
            } else {
                this.elements.audioSettings.classList.add('disabled');
            }
        }
    }
    
    /**
     * 预览音效
     */
    previewSound() {
        if (this.audioManager && this.elements.soundTypeSelect) {
            const soundType = this.elements.soundTypeSelect.value;
            this.audioManager.previewSound(soundType);
        }
    }
    
    /**
      * 更新音量显示
      */
     updateVolumeDisplay(volume) {
         if (this.elements.volumeValue) {
             this.elements.volumeValue.textContent = Math.round(volume * 100) + '%';
         }
     }
     
     /**
      * 从配置加载音频设置到界面
      */
     loadAudioSettingsFromConfig() {
         const audioSettings = this.audioManager.getSettings();

         // 设置音频开关状态
         if (this.elements.enableAudio) {
             this.elements.enableAudio.checked = audioSettings.isEnabled;
         }

         // 设置音效类型
         if (this.elements.soundTypeSelect) {
             this.elements.soundTypeSelect.value = audioSettings.soundType || 'bell';
         }

         // 设置音量
         if (this.elements.volumeSlider) {
             this.elements.volumeSlider.value = audioSettings.volume || 0.7;
             this.updateVolumeDisplay(audioSettings.volume || 0.7);
         }

         // 更新音频设置区域状态
         this.toggleAudioSettings();
     }
     
     /**
      * 保存音频设置
      */
     saveAudioSettings() {
         if (this.elements.enableAudio) {
             this.audioManager.setEnabled(this.elements.enableAudio.checked);
         }
         
         if (this.elements.soundTypeSelect) {
             this.audioManager.setSoundType(this.elements.soundTypeSelect.value);
         }
         
         if (this.elements.volumeSlider) {
             this.audioManager.setVolume(parseFloat(this.elements.volumeSlider.value));
         }
         
         // 保存到本地存储
         this.audioManager.saveSettings();
     }
     
     /**
      * 设置主题相关事件监听器
      */
     setupThemeEventListeners() {
         // 主题色彩选择
         if (this.elements.themeOptions) {
             this.elements.themeOptions.forEach(option => {
                 option.addEventListener('click', () => {
                     const theme = option.getAttribute('data-theme');
                     this.selectTheme(theme);
                 });
             });
         }
         
         // 字体大小选择
         if (this.elements.fontSizeRadios) {
             this.elements.fontSizeRadios.forEach(radio => {
                 radio.addEventListener('change', () => {
                     if (radio.checked) {
                         this.themeManager.setFontSize(radio.value);
                     }
                 });
             });
         }
         
         // 暗黑模式切换
         if (this.elements.darkModeToggle) {
             this.elements.darkModeToggle.addEventListener('change', () => {
                 this.themeManager.setDarkMode(this.elements.darkModeToggle.checked);
             });
         }
         
         // 进度环样式选择
         if (this.elements.progressStyleRadios) {
             this.elements.progressStyleRadios.forEach(radio => {
                 radio.addEventListener('change', () => {
                     if (radio.checked) {
                         this.themeManager.setProgressStyle(radio.value);
                     }
                 });
             });
         }
         
         // 初始化主题设置界面
         this.initThemeSettings();
     }
     
     /**
      * 选择主题
      */
     selectTheme(theme) {
         // 移除所有主题选项的选中状态
         if (this.elements.themeOptions) {
             this.elements.themeOptions.forEach(option => {
                 option.classList.remove('selected');
             });
         }
         
         // 添加选中状态到当前主题
         const selectedOption = document.querySelector(`[data-theme="${theme}"]`);
         if (selectedOption) {
             selectedOption.classList.add('selected');
         }
         
         // 应用主题
         this.themeManager.setTheme(theme);
     }
     
     /**
      * 初始化主题设置界面
      */
     initThemeSettings() {
         const themeSettings = this.themeManager.getSettings();
         
         // 设置当前主题选中状态
         this.selectTheme(themeSettings.theme);
         
         // 设置字体大小
         if (this.elements.fontSizeRadios) {
             this.elements.fontSizeRadios.forEach(radio => {
                 radio.checked = radio.value === themeSettings.fontSize;
             });
         }
         
         // 设置暗黑模式
         if (this.elements.darkModeToggle) {
             this.elements.darkModeToggle.checked = themeSettings.darkMode;
         }
         
         // 设置进度环样式
         if (this.elements.progressStyleRadios) {
             this.elements.progressStyleRadios.forEach(radio => {
                 radio.checked = radio.value === themeSettings.progressStyle;
             });
         }
     }
     
     /**
      * 从配置加载主题设置到界面
      */
     loadThemeSettingsFromConfig() {
         this.initThemeSettings();
     }
     
     /**
      * 保存主题设置
      */
     saveThemeSettings() {
         // 主题设置会在用户操作时自动保存，这里不需要额外操作
         // ThemeManager会自动处理设置的保存
     }
     
     /**
     * 设置通知相关事件监听器
     */
    setupNotificationEventListeners() {
        // 桌面通知开关
        if (this.elements.enableDesktopNotifications) {
            this.elements.enableDesktopNotifications.addEventListener('change', () => {
                this.updateNotificationSettings();
            });
        }
        
        // 自定义通知文案开关
        if (this.elements.enableCustomNotifications) {
            this.elements.enableCustomNotifications.addEventListener('change', () => {
                this.toggleCustomNotificationContent();
                this.updateNotificationSettings();
            });
        }
        
        // 自定义通知内容输入
        const customInputs = [
            this.elements.customNotificationTitle,
            this.elements.customWorkCompleteText,
            this.elements.customShortBreakCompleteText,
            this.elements.customLongBreakCompleteText
        ];
        
        customInputs.forEach(input => {
            if (input) {
                input.addEventListener('input', () => {
                    this.updateNotificationSettings();
                });
            }
        });
        
        // 通知交互选项
        if (this.elements.notificationRequireInteraction) {
            this.elements.notificationRequireInteraction.addEventListener('change', () => {
                this.updateNotificationSettings();
            });
        }
        
        // 通知自动关闭时间
        if (this.elements.notificationAutoCloseTime) {
            this.elements.notificationAutoCloseTime.addEventListener('change', () => {
                this.updateNotificationSettings();
            });
        }
        
        // 初始化通知设置界面
        this.initNotificationSettings();
    }
    
    /**
     * 初始化通知设置界面
     */
    initNotificationSettings() {
        const notificationSettings = this.getNotificationSettings();
        
        // 设置桌面通知开关
        if (this.elements.enableDesktopNotifications) {
            this.elements.enableDesktopNotifications.checked = notificationSettings.enabled;
        }
        
        // 设置自定义通知文案开关
        if (this.elements.enableCustomNotifications) {
            this.elements.enableCustomNotifications.checked = notificationSettings.customText;
        }
        
        // 设置自定义通知内容
        if (this.elements.customNotificationTitle) {
            this.elements.customNotificationTitle.value = notificationSettings.customTitle || '番茄时钟';
        }
        
        if (this.elements.customWorkCompleteText) {
            this.elements.customWorkCompleteText.value = notificationSettings.customMessages.work || '工作时间结束！该休息一下了 🎉';
        }
        
        if (this.elements.customShortBreakCompleteText) {
            this.elements.customShortBreakCompleteText.value = notificationSettings.customMessages.short_break || '短休息结束！继续加油工作 💪';
        }
        
        if (this.elements.customLongBreakCompleteText) {
            this.elements.customLongBreakCompleteText.value = notificationSettings.customMessages.long_break || '长休息结束！准备开始新的番茄周期 🍅';
        }
        
        // 设置通知交互选项
        if (this.elements.notificationRequireInteraction) {
            this.elements.notificationRequireInteraction.checked = notificationSettings.requireInteraction;
        }
        
        // 设置通知自动关闭时间
        if (this.elements.notificationAutoCloseTime) {
            this.elements.notificationAutoCloseTime.value = notificationSettings.autoClose || 5000;
        }
        
        // 初始化自定义通知内容显示状态
        this.toggleCustomNotificationContent();
    }
    
    /**
     * 切换自定义通知内容显示状态
     */
    toggleCustomNotificationContent() {
        const enabled = this.elements.enableCustomNotifications && this.elements.enableCustomNotifications.checked;
        if (this.elements.customNotificationContent) {
            if (enabled) {
                this.elements.customNotificationContent.classList.remove('disabled');
            } else {
                this.elements.customNotificationContent.classList.add('disabled');
            }
        }
    }
    
    /**
     * 更新通知设置
     */
    updateNotificationSettings() {
        const settings = {
            enabled: this.elements.enableDesktopNotifications ? this.elements.enableDesktopNotifications.checked : true,
            customText: this.elements.enableCustomNotifications ? this.elements.enableCustomNotifications.checked : false,
            customTitle: this.elements.customNotificationTitle ? this.elements.customNotificationTitle.value : '番茄时钟',
            customMessages: {
                work: this.elements.customWorkCompleteText ? this.elements.customWorkCompleteText.value : '工作时间结束！该休息一下了 🎉',
                short_break: this.elements.customShortBreakCompleteText ? this.elements.customShortBreakCompleteText.value : '短休息结束！继续加油工作 💪',
                long_break: this.elements.customLongBreakCompleteText ? this.elements.customLongBreakCompleteText.value : '长休息结束！准备开始新的番茄周期 🍅'
            },
            requireInteraction: this.elements.notificationRequireInteraction ? this.elements.notificationRequireInteraction.checked : false,
            autoClose: this.elements.notificationAutoCloseTime ? parseInt(this.elements.notificationAutoCloseTime.value) : 5000
        };
        
        this.saveNotificationSettings(settings);
    }
    
    /**
     * 显示通知权限引导（增强版）
     */
    showNotificationPermissionGuide() {
        if ('Notification' in window && Notification.permission === 'default') {
            const guide = document.createElement('div');
            guide.className = 'notification-permission-guide';
            guide.innerHTML = `
                <div class="guide-content">
                    <div class="guide-header">
                        <div class="guide-icon">🔔</div>
                        <button class="guide-close" id="guideCloseBtn">×</button>
                    </div>
                    <div class="guide-text">
                        <h4>开启桌面通知权限</h4>
                        <p>允许番茄时钟发送桌面通知，让您在专注工作时不错过任何重要提醒</p>
                        <div class="guide-benefits">
                            <div class="benefit-item">
                                <span class="benefit-icon">⏰</span>
                                <span>及时提醒时间到达</span>
                            </div>
                            <div class="benefit-item">
                                <span class="benefit-icon">🎯</span>
                                <span>保持专注不被打扰</span>
                            </div>
                            <div class="benefit-item">
                                <span class="benefit-icon">🔄</span>
                                <span>自动切换工作状态</span>
                            </div>
                        </div>
                    </div>
                    <div class="guide-actions">
                        <button class="guide-btn allow-btn" id="allowNotificationBtn">
                            <span class="btn-icon">✓</span>
                            允许通知
                        </button>
                        <button class="guide-btn dismiss-btn" id="dismissGuideBtn">
                            <span class="btn-icon">⏭</span>
                            暂时跳过
                        </button>
                    </div>
                </div>
            `;
            
            // 添加样式
            guide.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: white;
                border-radius: 16px;
                box-shadow: 0 8px 32px rgba(0,0,0,0.2);
                padding: 24px;
                max-width: 380px;
                z-index: 10000;
                border-left: 4px solid #ff6b6b;
                animation: slideInRight 0.3s ease-out;
            `;
            
            // 添加动画样式
            if (!document.querySelector('#notificationGuideStyles')) {
                const style = document.createElement('style');
                style.id = 'notificationGuideStyles';
                style.textContent = `
                    @keyframes slideInRight {
                        from {
                            transform: translateX(100%);
                            opacity: 0;
                        }
                        to {
                            transform: translateX(0);
                            opacity: 1;
                        }
                    }
                    .guide-header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-bottom: 16px;
                    }
                    .guide-icon {
                        font-size: 24px;
                    }
                    .guide-close {
                        background: none;
                        border: none;
                        font-size: 20px;
                        cursor: pointer;
                        color: #999;
                        padding: 4px;
                        border-radius: 4px;
                    }
                    .guide-close:hover {
                        background: #f0f0f0;
                        color: #666;
                    }
                    .guide-text h4 {
                        margin: 0 0 8px 0;
                        color: #333;
                        font-size: 18px;
                    }
                    .guide-text p {
                        margin: 0 0 16px 0;
                        color: #666;
                        line-height: 1.5;
                    }
                    .guide-benefits {
                        margin-bottom: 20px;
                    }
                    .benefit-item {
                        display: flex;
                        align-items: center;
                        margin-bottom: 8px;
                        font-size: 14px;
                        color: #555;
                    }
                    .benefit-icon {
                        margin-right: 8px;
                        font-size: 16px;
                    }
                    .guide-actions {
                        display: flex;
                        gap: 12px;
                    }
                    .guide-btn {
                        flex: 1;
                        padding: 12px 16px;
                        border: none;
                        border-radius: 8px;
                        font-size: 14px;
                        font-weight: 500;
                        cursor: pointer;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        gap: 6px;
                        transition: all 0.2s ease;
                    }
                    .allow-btn {
                        background: #4CAF50;
                        color: white;
                    }
                    .allow-btn:hover {
                        background: #45a049;
                        transform: translateY(-1px);
                    }
                    .dismiss-btn {
                        background: #f5f5f5;
                        color: #666;
                    }
                    .dismiss-btn:hover {
                        background: #e0e0e0;
                        transform: translateY(-1px);
                    }
                `;
                document.head.appendChild(style);
            }
            
            document.body.appendChild(guide);
            
            // 事件监听
            document.getElementById('allowNotificationBtn').addEventListener('click', async () => {
                try {
                    const permission = await Notification.requestPermission();
                    if (permission === 'granted') {
                        this.showNotification('桌面通知权限已开启！现在您可以收到时间提醒了 🎉', 'success');
                        
                        // 发送测试通知
                        setTimeout(() => {
                            new Notification('番茄时钟', {
                                body: '通知功能已准备就绪！',
                                icon: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text y=".9em" font-size="90">🍅</text></svg>'
                            });
                        }, 1000);
                    }
                } catch (error) {
                    console.error('Request notification permission error:', error);
                    this.showNotification('开启通知权限失败，请手动在浏览器设置中允许', 'error');
                }
                guide.remove();
            });
            
            document.getElementById('dismissGuideBtn').addEventListener('click', () => {
                guide.remove();
            });
            
            document.getElementById('guideCloseBtn').addEventListener('click', () => {
                guide.remove();
            });
            
            // 10秒后自动隐藏
            setTimeout(() => {
                if (guide.parentNode) {
                    guide.remove();
                }
            }, 15000);
        }
    }
    
    /**
     * 设置数据管理事件监听器
     */
    setupDataManagementEventListeners() {
         // 导出设置按钮
         if (this.elements.exportSettingsBtn) {
             this.elements.exportSettingsBtn.addEventListener('click', () => {
                 this.exportSettings();
             });
         }
         
         // 导入设置按钮
         if (this.elements.importSettingsBtn) {
             this.elements.importSettingsBtn.addEventListener('click', () => {
                 this.elements.importFileInput.click();
             });
         }
         
         // 文件输入变化
         if (this.elements.importFileInput) {
             this.elements.importFileInput.accept = '.json,.txt';
             this.elements.importFileInput.addEventListener('change', (event) => {
                 this.importSettings(event);
             });
         }
         
         // 重置设置按钮
         if (this.elements.resetSettingsBtn) {
             this.elements.resetSettingsBtn.addEventListener('click', () => {
                 this.resetSettings();
             });
         }
         
         // 清除数据按钮
         if (this.elements.clearDataBtn) {
             this.elements.clearDataBtn.addEventListener('click', () => {
                 this.clearAllData();
             });
         }
         
         // 初始化存储信息显示
         this.updateStorageInfo();
     }
     
     /**
     * 导出设置
     */
    exportSettings() {
        try {
            if (!this.settingsManager) {
                this.settingsManager = new SettingsManager();
            }
            
            const settings = this.settingsManager.exportSettings();
            
            // 创建用户友好的文本格式
            const friendlyFormat = this.createFriendlyExportFormat(settings);
            const dataBlob = new Blob([friendlyFormat], { type: 'text/plain;charset=utf-8' });
            
            const link = document.createElement('a');
            link.href = URL.createObjectURL(dataBlob);
            link.download = `番茄时钟设置备份-${new Date().toISOString().split('T')[0]}.txt`;
            link.click();
            
            this.showNotification('设置导出成功！', 'success');
        } catch (error) {
            console.error('Export settings error:', error);
            this.showNotification('导出设置失败，请重试', 'error');
        }
    }
    
    /**
     * 创建用户友好的导出格式
     */
    createFriendlyExportFormat(settings) {
        const formatTime = (seconds) => {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;
            
            if (hours > 0) {
                return `${hours}小时${minutes}分钟${secs}秒`;
            } else if (minutes > 0) {
                return `${minutes}分钟${secs}秒`;
            } else {
                return `${secs}秒`;
            }
        };
        
        const themeNames = {
            'default': '经典红',
            'blue': '海洋蓝',
            'green': '森林绿',
            'purple': '优雅紫',
            'orange': '活力橙'
        };
        
        const fontSizeNames = {
            'small': '小',
            'medium': '中',
            'large': '大'
        };
        
        const progressStyleNames = {
            'classic': '经典',
            'modern': '现代',
            'minimal': '简约'
        };
        
        let content = `番茄时钟设置备份\n`;
        content += `导出时间：${new Date().toLocaleString('zh-CN')}\n`;
        content += `\n=== 时间设置 ===\n`;
        content += `工作时间：${formatTime(settings.time.workTime)}\n`;
        content += `短休息时间：${formatTime(settings.time.shortBreak)}\n`;
        content += `长休息时间：${formatTime(settings.time.longBreak)}\n`;
        content += `长休息触发间隔：${settings.time.longBreakCycle}个番茄\n`;
        
        content += `\n=== 功能设置 ===\n`;
        content += `启用短休息：${settings.features.enableShortBreak ? '是' : '否'}\n`;
        content += `启用长休息：${settings.features.enableLongBreak ? '是' : '否'}\n`;
        
        content += `\n=== 音频设置 ===\n`;
        content += `启用音效：${settings.audio.enabled ? '是' : '否'}\n`;
        content += `音效类型：${settings.audio.soundType}\n`;
        content += `音量：${Math.round(settings.audio.volume * 100)}%\n`;
        
        content += `\n=== 主题设置 ===\n`;
        content += `色彩方案：${themeNames[settings.theme.theme] || settings.theme.theme}\n`;
        content += `字体大小：${fontSizeNames[settings.theme.fontSize] || settings.theme.fontSize}\n`;
        content += `暗黑模式：${settings.theme.darkMode ? '开启' : '关闭'}\n`;
        content += `进度环样式：${progressStyleNames[settings.theme.progressStyle] || settings.theme.progressStyle}\n`;
        
        content += `\n=== 统计数据 ===\n`;
        content += `今日完成番茄：${settings.stats.dailyPomodoros}个\n`;
        content += `总完成番茄：${settings.stats.totalPomodoros}个\n`;
        content += `连续天数：${settings.stats.streakDays}天\n`;
        
        content += `\n=== 技术信息 ===\n`;
        content += `应用版本：${settings.app.version}\n`;
        content += `最后更新：${new Date(settings.app.lastUpdated).toLocaleString('zh-CN')}\n`;
        
        content += `\n\n--- JSON数据（用于导入） ---\n`;
        content += JSON.stringify(settings, null, 2);
        
        return content;
    }
     
     /**
      * 导入设置
      */
     importSettings(event) {
         const file = event.target.files[0];
         if (!file) return;
         
         const reader = new FileReader();
         reader.onload = (e) => {
             try {
                 let settings;
                 const content = e.target.result;
                 
                 // 尝试解析JSON格式
                 if (file.name.endsWith('.json')) {
                     settings = JSON.parse(content);
                 } else if (file.name.endsWith('.txt')) {
                     // 从文本格式中提取JSON数据
                     const jsonMatch = content.match(/--- JSON数据（用于导入） ---\s*\n([\s\S]+)$/);
                     if (jsonMatch && jsonMatch[1]) {
                         settings = JSON.parse(jsonMatch[1].trim());
                     } else {
                         throw new Error('文本文件中未找到有效的JSON数据');
                     }
                 } else {
                     // 尝试直接解析为JSON
                     settings = JSON.parse(content);
                 }
                 
                 if (!this.settingsManager) {
                     this.settingsManager = new SettingsManager();
                 }
                 
                 // 验证设置格式
                 if (this.settingsManager.validateSettings(settings)) {
                     this.settingsManager.importSettings(settings);
                     
                     // 重新加载所有设置到界面
                     this.loadSettingsFromConfig();
                     
                     // 应用新设置
                     this.applyImportedSettings();
                     
                     this.showNotification('设置导入成功！', 'success');
                     this.updateStorageInfo();
                 } else {
                     this.showNotification('设置文件格式无效', 'error');
                 }
             } catch (error) {
                 console.error('Import settings error:', error);
                 this.showNotification('导入设置失败，文件格式错误', 'error');
             }
         };
         
         reader.readAsText(file);
         // 清空文件输入，允许重复选择同一文件
         event.target.value = '';
     }
     
     /**
      * 应用导入的设置
      */
     applyImportedSettings() {
         // 重新初始化各个管理器
         if (this.audioManager) {
             this.audioManager.loadSettings();
         }
         
         if (this.themeManager) {
             this.themeManager.loadSettings();
             this.themeManager.applyTheme();
         }
         
         // 延迟更新UI确保设置已应用
         setTimeout(() => {
             this.updateUI();
             this.refreshUIState();
         }, 100);
     }
     
     /**
      * 重置设置
      */
     resetSettings() {
         if (confirm('确定要重置所有设置吗？这将恢复到默认配置。')) {
             try {
                 if (!this.settingsManager) {
                     this.settingsManager = new SettingsManager();
                 }
                 
                 this.settingsManager.resetSettings();
                 
                 // 重新加载设置
                 this.loadSettingsFromConfig();
                 this.applyImportedSettings();
                 
                 this.showNotification('设置已重置为默认值', 'success');
                 this.updateStorageInfo();
             } catch (error) {
                 console.error('Reset settings error:', error);
                 this.showNotification('重置设置失败，请重试', 'error');
             }
         }
     }
     
     /**
      * 清除所有数据
      */
     clearAllData() {
         if (confirm('确定要清除所有数据吗？这将删除所有设置和统计数据，且无法恢复！')) {
             try {
                 if (!this.settingsManager) {
                     this.settingsManager = new SettingsManager();
                 }
                 
                 this.settingsManager.clearAllData();
                 
                 // 重新加载默认设置
                 this.loadSettingsFromConfig();
                 this.applyImportedSettings();
                 
                 this.showNotification('所有数据已清除', 'success');
                 this.updateStorageInfo();
             } catch (error) {
                 console.error('Clear data error:', error);
                 this.showNotification('清除数据失败，请重试', 'error');
             }
         }
     }
     
     /**
      * 更新存储信息显示
      */
     updateStorageInfo() {
         try {
             if (!this.settingsManager) {
                 this.settingsManager = new SettingsManager();
             }
             
             const storageInfo = this.settingsManager.getStorageInfo();
             
             if (this.elements.settingsSize) {
                 this.elements.settingsSize.textContent = this.formatBytes(storageInfo.settingsSize);
             }
             
             if (this.elements.totalUsed) {
                 this.elements.totalUsed.textContent = this.formatBytes(storageInfo.totalUsed);
             }
         } catch (error) {
             console.error('Update storage info error:', error);
             if (this.elements.settingsSize) {
                 this.elements.settingsSize.textContent = '计算失败';
             }
             if (this.elements.totalUsed) {
                 this.elements.totalUsed.textContent = '计算失败';
             }
         }
     }
     
     /**
      * 格式化字节大小
      */
     formatBytes(bytes) {
         if (bytes === 0) return '0 B';
         
         const k = 1024;
         const sizes = ['B', 'KB', 'MB', 'GB'];
         const i = Math.floor(Math.log(bytes) / Math.log(k));
         
         return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
     }
     
     /**
      * 显示通知消息
      */
     showNotification(message, type = 'info') {
         // 创建通知元素
         const notification = document.createElement('div');
         notification.className = `notification notification-${type}`;
         notification.textContent = message;
         
         // 添加样式
         notification.style.cssText = `
             position: fixed;
             top: 20px;
             right: 20px;
             padding: 12px 20px;
             border-radius: 8px;
             color: white;
             font-weight: 500;
             z-index: 10000;
             opacity: 0;
             transform: translateX(100%);
             transition: all 0.3s ease;
             max-width: 300px;
             word-wrap: break-word;
         `;
         
         // 设置背景色
         switch (type) {
             case 'success':
                 notification.style.backgroundColor = '#4CAF50';
                 break;
             case 'error':
                 notification.style.backgroundColor = '#F44336';
                 break;
             case 'warning':
                 notification.style.backgroundColor = '#FF9800';
                 break;
             default:
                 notification.style.backgroundColor = '#2196F3';
         }
         
         // 添加到页面
         document.body.appendChild(notification);
         
         // 显示动画
         setTimeout(() => {
             notification.style.opacity = '1';
             notification.style.transform = 'translateX(0)';
         }, 100);
         
         // 自动隐藏
         setTimeout(() => {
             notification.style.opacity = '0';
             notification.style.transform = 'translateX(100%)';
             setTimeout(() => {
                 if (notification.parentNode) {
                     notification.parentNode.removeChild(notification);
                 }
             }, 300);
         }, 3000);
     }
     
     // ==================== 统计功能相关方法 ====================
     
     /**
      * 设置统计面板事件监听器
      */
     setupStatisticsEventListeners() {
         // 统计按钮
         if (this.elements.statsBtn) {
             this.elements.statsBtn.addEventListener('click', () => {
                 this.openStatistics();
             });
         }
         
         // 关闭统计面板按钮
         if (this.elements.closeStatsBtn) {
             this.elements.closeStatsBtn.addEventListener('click', () => {
                 this.closeStatistics();
             });
         }
         
         // 趋势图表切换按钮
         if (this.elements.trendChart7Btn) {
             this.elements.trendChart7Btn.addEventListener('click', () => {
                 this.showTrendChart(7);
             });
         }
         
         if (this.elements.trendChart30Btn) {
             this.elements.trendChart30Btn.addEventListener('click', () => {
                 this.showTrendChart(30);
             });
         }
         
         // 导出统计数据
         if (this.elements.exportStatsBtn) {
             this.elements.exportStatsBtn.addEventListener('click', () => {
                 this.exportStatistics();
             });
         }
         
         // 重置统计数据
         if (this.elements.resetStatsBtn) {
             this.elements.resetStatsBtn.addEventListener('click', () => {
                 this.resetStatistics();
             });
         }
     }
     
     /**
      * 记录统计数据
      */
     recordStatistics(data) {
         try {
             if (data.completedState === 'work') {
                 // 记录完成的番茄时钟
                 this.statisticsManager.recordPomodoro({
                     duration: data.duration || 25 * 60, // 默认25分钟
                     timestamp: Date.now(),
                     type: 'work'
                 });
                 
                 console.log('Pomodoro recorded in statistics');
             }
         } catch (error) {
             console.error('Error recording statistics:', error);
         }
     }
     
     /**
      * 打开统计面板
      */
     openStatistics() {
         try {
             if (this.elements.statisticsModal) {
                 this.elements.statisticsModal.classList.add('show');
                 this.updateStatisticsDisplay();
                 this.showTrendChart(7); // 默认显示7天趋势
                 this.showHourlyDistribution();
             }
         } catch (error) {
             console.error('Error opening statistics:', error);
             this.showNotification('打开统计面板失败', 'error');
         }
     }
     
     /**
      * 关闭统计面板
      */
     closeStatistics() {
         if (this.elements.statisticsModal) {
             this.elements.statisticsModal.classList.remove('show');
         }
     }
     
     /**
      * 更新统计数据显示
      */
     updateStatisticsDisplay() {
         try {
             const todayStats = this.statisticsManager.getTodayStats();
             const weekStats = this.statisticsManager.getWeekStats();
             const totalStats = this.statisticsManager.getTotalStats();
             const efficiency = this.statisticsManager.getEfficiencyAnalysis();
             
             // 今日统计
             if (this.elements.todayPomodoros) {
                 this.elements.todayPomodoros.textContent = todayStats.pomodoros;
             }
             if (this.elements.todayFocusTime) {
                 this.elements.todayFocusTime.textContent = this.formatDuration(todayStats.focusTime);
             }
             
             // 本周统计
             if (this.elements.weekPomodoros) {
                 this.elements.weekPomodoros.textContent = weekStats.pomodoros;
             }
             if (this.elements.weekFocusTime) {
                 this.elements.weekFocusTime.textContent = this.formatDuration(weekStats.focusTime);
             }
             
             // 总计统计
             if (this.elements.totalPomodoros) {
                 this.elements.totalPomodoros.textContent = totalStats.pomodoros;
             }
             if (this.elements.totalFocusTime) {
                 this.elements.totalFocusTime.textContent = this.formatDuration(totalStats.focusTime);
             }
             
             // 连续天数
             if (this.elements.streakDays) {
                 this.elements.streakDays.textContent = totalStats.streakDays;
             }
             
             // 效率分析
             if (this.elements.avgDailyPomodoros) {
                 this.elements.avgDailyPomodoros.textContent = efficiency.avgDailyPomodoros.toFixed(1);
             }
             if (this.elements.peakHour) {
                 this.elements.peakHour.textContent = efficiency.peakHour + ':00';
             }
             if (this.elements.focusConsistency) {
                 this.elements.focusConsistency.textContent = efficiency.consistency.toFixed(1) + '%';
             }
             if (this.elements.trendStatus) {
                 this.elements.trendStatus.textContent = this.getTrendText(efficiency.trend);
                 this.elements.trendStatus.setAttribute('data-trend', efficiency.trend);
             }
             
         } catch (error) {
             console.error('Error updating statistics display:', error);
         }
     }
     
     /**
      * 显示趋势图表
      */
     showTrendChart(days) {
         try {
             // 更新按钮状态
             if (this.elements.trendChart7Btn) {
                 this.elements.trendChart7Btn.classList.toggle('active', days === 7);
             }
             if (this.elements.trendChart30Btn) {
                 this.elements.trendChart30Btn.classList.toggle('active', days === 30);
             }
             
             const trendData = this.statisticsManager.getTrendData(days);
             this.renderTrendChart(trendData, days);
             
         } catch (error) {
             console.error('Error showing trend chart:', error);
         }
     }
     
     /**
      * 渲染趋势图表
      */
     renderTrendChart(data, days) {
         const canvas = document.getElementById('trendChart');
         if (!canvas) return;
         
         const ctx = canvas.getContext('2d');
         const width = canvas.width = canvas.offsetWidth;
         const height = canvas.height = canvas.offsetHeight;
         
         // 清空画布
         ctx.clearRect(0, 0, width, height);
         
         if (!data || data.length === 0) {
             ctx.fillStyle = '#666';
             ctx.font = '14px Arial';
             ctx.textAlign = 'center';
             ctx.fillText('暂无数据', width / 2, height / 2);
             return;
         }
         
         // 绘制简单的折线图
         const padding = 40;
         const chartWidth = width - padding * 2;
         const chartHeight = height - padding * 2;
         
         const maxValue = Math.max(...data.map(d => d.pomodoros), 1);
         const stepX = chartWidth / (data.length - 1 || 1);
         
         // 绘制网格线
         ctx.strokeStyle = '#e0e0e0';
         ctx.lineWidth = 1;
         for (let i = 0; i <= 5; i++) {
             const y = padding + (chartHeight / 5) * i;
             ctx.beginPath();
             ctx.moveTo(padding, y);
             ctx.lineTo(width - padding, y);
             ctx.stroke();
         }
         
         // 绘制数据线
         ctx.strokeStyle = '#8b5cf6';
         ctx.lineWidth = 2;
         ctx.beginPath();
         
         data.forEach((point, index) => {
             const x = padding + stepX * index;
             const y = padding + chartHeight - (point.pomodoros / maxValue) * chartHeight;
             
             if (index === 0) {
                 ctx.moveTo(x, y);
             } else {
                 ctx.lineTo(x, y);
             }
         });
         
         ctx.stroke();
         
         // 绘制数据点
         ctx.fillStyle = '#8b5cf6';
         data.forEach((point, index) => {
             const x = padding + stepX * index;
             const y = padding + chartHeight - (point.pomodoros / maxValue) * chartHeight;
             
             ctx.beginPath();
             ctx.arc(x, y, 4, 0, Math.PI * 2);
             ctx.fill();
         });
     }
     
     /**
      * 显示时段分布图表
      */
     showHourlyDistribution() {
         try {
             const distribution = this.statisticsManager.getHourlyDistribution();
             this.renderHourlyChart(distribution);
         } catch (error) {
             console.error('Error showing hourly distribution:', error);
         }
     }
     
     /**
      * 渲染时段分布图表
      */
     renderHourlyChart(data) {
         const canvas = document.getElementById('hourlyChart');
         if (!canvas) return;
         
         const ctx = canvas.getContext('2d');
         const width = canvas.width = canvas.offsetWidth;
         const height = canvas.height = canvas.offsetHeight;
         
         // 清空画布
         ctx.clearRect(0, 0, width, height);
         
         if (!data || data.length === 0) {
             ctx.fillStyle = '#666';
             ctx.font = '14px Arial';
             ctx.textAlign = 'center';
             ctx.fillText('暂无数据', width / 2, height / 2);
             return;
         }
         
         // 绘制简单的柱状图
         const padding = 40;
         const chartWidth = width - padding * 2;
         const chartHeight = height - padding * 2;
         
         const maxValue = Math.max(...data.map(d => d.count), 1);
         const barWidth = chartWidth / 24;
         
         // 绘制柱状图
         data.forEach((item, index) => {
             const barHeight = (item.count / maxValue) * chartHeight;
             const x = padding + index * barWidth;
             const y = padding + chartHeight - barHeight;
             
             ctx.fillStyle = item.count > 0 ? '#8b5cf6' : '#e0e0e0';
             ctx.fillRect(x, y, barWidth - 2, barHeight);
         });
     }
     
     /**
      * 导出统计数据
      */
     exportStatistics() {
         try {
             const stats = this.statisticsManager.exportStatistics();
             const dataStr = JSON.stringify(stats, null, 2);
             const dataBlob = new Blob([dataStr], { type: 'application/json' });
             
             const link = document.createElement('a');
             link.href = URL.createObjectURL(dataBlob);
             link.download = `pomodoro-statistics-${new Date().toISOString().split('T')[0]}.json`;
             link.click();
             
             this.showNotification('统计数据导出成功', 'success');
         } catch (error) {
             console.error('Error exporting statistics:', error);
             this.showNotification('导出统计数据失败', 'error');
         }
     }
     
     /**
      * 重置统计数据
      */
     resetStatistics() {
         if (confirm('确定要重置所有统计数据吗？此操作无法撤销！')) {
             try {
                 this.statisticsManager.resetStatistics();
                 this.updateStatisticsDisplay();
                 this.showTrendChart(7);
                 this.showHourlyDistribution();
                 this.showNotification('统计数据已重置', 'success');
             } catch (error) {
                 console.error('Error resetting statistics:', error);
                 this.showNotification('重置统计数据失败', 'error');
             }
         }
     }
     
     /**
      * 格式化时长显示
      */
     formatDuration(seconds) {
         const hours = Math.floor(seconds / 3600);
         const minutes = Math.floor((seconds % 3600) / 60);
         
         if (hours > 0) {
             return `${hours}h ${minutes}m`;
         } else {
             return `${minutes}m`;
         }
     }
     
     /**
     * 获取趋势文本
     */
    getTrendText(trend) {
        switch (trend) {
            case 'improving':
                return '上升趋势';
            case 'declining':
                return '下降趋势';
            case 'stable':
            default:
                return '保持稳定';
        }
    }
    
    // ==================== 任务管理相关方法 ====================
    
    /**
     * 设置任务管理事件监听器
     */
    setupTasksEventListeners() {
        // 任务按钮
        if (this.elements.tasksBtn) {
            this.elements.tasksBtn.addEventListener('click', () => {
                this.openTasks();
            });
        }
        
        // 关闭任务弹窗
        if (this.elements.closeTasksBtn) {
            this.elements.closeTasksBtn.addEventListener('click', () => {
                this.closeTasks();
            });
        }
        
        // 添加任务
        if (this.elements.addTaskBtn) {
            this.elements.addTaskBtn.addEventListener('click', () => {
                this.addTask();
            });
        }
        
        // 任务输入框回车添加
        if (this.elements.taskInput) {
            this.elements.taskInput.addEventListener('keypress', (event) => {
                if (event.key === 'Enter') {
                    this.addTask();
                }
            });
        }
        
        // 筛选按钮
        if (this.elements.filterAllBtn) {
            this.elements.filterAllBtn.addEventListener('click', () => {
                this.filterTasks('all');
            });
        }
        
        if (this.elements.filterActiveBtn) {
            this.elements.filterActiveBtn.addEventListener('click', () => {
                this.filterTasks('active');
            });
        }
        
        if (this.elements.filterCompletedBtn) {
            this.elements.filterCompletedBtn.addEventListener('click', () => {
                this.filterTasks('completed');
            });
        }
        
        // 清除已完成任务
        if (this.elements.clearCompletedBtn) {
            this.elements.clearCompletedBtn.addEventListener('click', () => {
                this.clearCompletedTasks();
            });
        }
        
        // 监听任务管理器事件
        this.taskManager.addListener((event, data) => {
            switch (event) {
                case 'tasksUpdated':
                    this.updateTasksDisplay();
                    break;
                case 'currentTaskChanged':
                    this.updateCurrentTaskDisplay(data.currentTask);
                    break;
            }
        });
    }
    
    /**
     * 打开任务管理面板
     */
    openTasks() {
        if (this.elements.tasksModal) {
            this.elements.tasksModal.classList.add('show');
            this.updateTasksDisplay();
            
            // 聚焦到输入框
            if (this.elements.taskInput) {
                setTimeout(() => {
                    this.elements.taskInput.focus();
                }, 100);
            }
        }
    }
    
    /**
     * 关闭任务管理面板
     */
    closeTasks() {
        if (this.elements.tasksModal) {
            this.elements.tasksModal.classList.remove('show');
        }
    }
    
    /**
     * 添加新任务
     */
    addTask() {
        const input = this.elements.taskInput;
        if (!input) return;
        
        const taskName = input.value.trim();
        if (!taskName) {
            this.showNotification('请输入任务名称', 'warning');
            return;
        }
        
        try {
            this.taskManager.createTask(taskName);
            input.value = '';
            this.showNotification('任务添加成功', 'success');
        } catch (error) {
            console.error('Error adding task:', error);
            this.showNotification('添加任务失败', 'error');
        }
    }
    
    /**
     * 筛选任务
     */
    filterTasks(filter) {
        // 更新筛选按钮状态
        const filterButtons = [
            this.elements.filterAllBtn,
            this.elements.filterActiveBtn,
            this.elements.filterCompletedBtn
        ];
        
        filterButtons.forEach(btn => {
            if (btn) btn.classList.remove('active');
        });
        
        switch (filter) {
            case 'all':
                if (this.elements.filterAllBtn) {
                    this.elements.filterAllBtn.classList.add('active');
                }
                break;
            case 'active':
                if (this.elements.filterActiveBtn) {
                    this.elements.filterActiveBtn.classList.add('active');
                }
                break;
            case 'completed':
                if (this.elements.filterCompletedBtn) {
                    this.elements.filterCompletedBtn.classList.add('active');
                }
                break;
        }
        
        this.currentTaskFilter = filter;
        this.updateTasksDisplay();
    }
    
    /**
     * 清除已完成的任务
     */
    clearCompletedTasks() {
        if (confirm('确定要清除所有已完成的任务吗？')) {
            try {
                this.taskManager.clearCompletedTasks();
                this.showNotification('已完成任务已清除', 'success');
            } catch (error) {
                console.error('Error clearing completed tasks:', error);
                this.showNotification('清除任务失败', 'error');
            }
        }
    }
    
    /**
     * 更新任务显示
     */
    updateTasksDisplay() {
        this.renderTasksList();
        this.updateTasksStats();
    }
    
    /**
     * 渲染任务列表
     */
    renderTasksList() {
        const tasksList = this.elements.tasksList;
        if (!tasksList) return;

        const tasks = this.taskManager.getAllTasks();
        const filter = this.currentTaskFilter || 'all';
        
        // 筛选任务
        let filteredTasks = tasks;
        switch (filter) {
            case 'active':
                filteredTasks = tasks.filter(task => !task.completed);
                break;
            case 'completed':
                filteredTasks = tasks.filter(task => task.completed);
                break;
        }
        
        // 清空列表
        tasksList.innerHTML = '';
        
        if (filteredTasks.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'tasks-empty';
            emptyState.innerHTML = `
                <div class="tasks-empty-icon">📝</div>
                <div class="tasks-empty-text">暂无任务</div>
                <div class="tasks-empty-hint">添加一个任务开始专注工作吧</div>
            `;
            tasksList.appendChild(emptyState);
            return;
        }
        
        // 渲染任务项
        filteredTasks.forEach(task => {
            const taskItem = this.createTaskElement(task);
            tasksList.appendChild(taskItem);
        });
    }
    
    /**
     * 创建任务元素
     */
    createTaskElement(task) {
        const taskItem = document.createElement('div');
        taskItem.className = 'task-item';
        taskItem.dataset.taskId = task.id;
        
        if (task.completed) {
            taskItem.classList.add('completed');
        }
        
        if (task.id === this.taskManager.getCurrentTaskId()) {
            taskItem.classList.add('current');
        }
        
        const progress = task.pomodorosCompleted > 0 ? 
            `${task.pomodorosCompleted} 个番茄时钟` : '未开始';
        
        taskItem.innerHTML = `
            <div class="task-checkbox ${task.completed ? 'checked' : ''}" 
                 onclick="pomodoroApp.toggleTaskComplete('${task.id}')"></div>
            <div class="task-content">
                <div class="task-name">${this.escapeHtml(task.name)}</div>
                <div class="task-progress">
                    <span>${progress}</span>
                    <div class="task-progress-bar">
                        <div class="task-progress-fill" style="width: ${task.pomodorosCompleted * 20}%"></div>
                    </div>
                </div>
            </div>
            <input type="text" class="task-edit-input" value="${this.escapeHtml(task.name)}" 
                   onkeypress="if(event.key==='Enter') pomodoroApp.saveTaskEdit('${task.id}', this.value)" 
                   onblur="pomodoroApp.cancelTaskEdit('${task.id}')">
            <div class="task-actions">
                <button class="task-action-btn select-task-btn" 
                        onclick="pomodoroApp.selectCurrentTask('${task.id}')" 
                        title="设为当前任务">🎯</button>
                <button class="task-action-btn edit-task-btn" 
                        onclick="pomodoroApp.editTask('${task.id}')" 
                        title="编辑任务">✏️</button>
                <button class="task-action-btn delete-task-btn" 
                        onclick="pomodoroApp.deleteTask('${task.id}')" 
                        title="删除任务">🗑️</button>
            </div>
            <div class="task-edit-actions">
                <button class="task-action-btn save-task-btn" 
                        onclick="pomodoroApp.saveTaskEdit('${task.id}', this.parentElement.previousElementSibling.value)" 
                        title="保存">✓</button>
                <button class="task-action-btn cancel-task-btn" 
                        onclick="pomodoroApp.cancelTaskEdit('${task.id}')" 
                        title="取消">✕</button>
            </div>
        `;
        
        return taskItem;
    }
    
    /**
     * 更新任务统计
     */
    updateTasksStats() {
        const stats = this.taskManager.getTaskStatistics();
        
        if (this.elements.totalTasksCount) {
            this.elements.totalTasksCount.textContent = stats.total;
        }
        
        if (this.elements.completedTasksCount) {
            this.elements.completedTasksCount.textContent = stats.completed;
        }
        
        if (this.elements.completionRate) {
            this.elements.completionRate.textContent = `${stats.completionRate}%`;
        }
    }
    
    /**
     * 切换任务完成状态
     */
    toggleTaskComplete(taskId) {
        try {
            this.taskManager.toggleTaskComplete(taskId);
            this.showNotification('任务状态已更新', 'success');
        } catch (error) {
            console.error('Error toggling task complete:', error);
            this.showNotification('更新任务状态失败', 'error');
        }
    }
    
    /**
     * 选择当前任务
     */
    selectCurrentTask(taskId) {
        try {
            this.taskManager.setCurrentTask(taskId);
            this.showNotification('当前任务已设置', 'success');
        } catch (error) {
            console.error('Error selecting current task:', error);
            this.showNotification('设置当前任务失败', 'error');
        }
    }
    
    /**
     * 编辑任务
     */
    editTask(taskId) {
        const taskItem = document.querySelector(`[data-task-id="${taskId}"]`);
        if (taskItem) {
            taskItem.classList.add('editing');
            const input = taskItem.querySelector('.task-edit-input');
            if (input) {
                input.focus();
                input.select();
            }
        }
    }
    
    /**
     * 保存任务编辑
     */
    saveTaskEdit(taskId, newName) {
        const trimmedName = newName.trim();
        if (!trimmedName) {
            this.showNotification('任务名称不能为空', 'warning');
            return;
        }
        
        try {
            this.taskManager.updateTask(taskId, { name: trimmedName });
            this.cancelTaskEdit(taskId);
            this.showNotification('任务已更新', 'success');
        } catch (error) {
            console.error('Error updating task:', error);
            this.showNotification('更新任务失败', 'error');
        }
    }
    
    /**
     * 取消任务编辑
     */
    cancelTaskEdit(taskId) {
        const taskItem = document.querySelector(`[data-task-id="${taskId}"]`);
        if (taskItem) {
            taskItem.classList.remove('editing');
        }
    }
    
    /**
     * 删除任务
     */
    deleteTask(taskId) {
        if (confirm('确定要删除这个任务吗？')) {
            try {
                this.taskManager.deleteTask(taskId);
                this.showNotification('任务已删除', 'success');
            } catch (error) {
                console.error('Error deleting task:', error);
                this.showNotification('删除任务失败', 'error');
            }
        }
    }
    
    /**
     * 更新当前任务显示
     */
    updateCurrentTaskDisplay(task) {
        // 更新任务列表中的当前任务标识
        const taskItems = document.querySelectorAll('.task-item');
        taskItems.forEach(item => {
            item.classList.remove('current');
        });
        
        if (task) {
            const currentTaskItem = document.querySelector(`[data-task-id="${task.id}"]`);
            if (currentTaskItem) {
                currentTaskItem.classList.add('current');
            }
        }
    }
    
    /**
     * 记录任务相关的番茄时钟完成
     */
    recordTaskPomodoro() {
        const currentTask = this.taskManager.getCurrentTask();
        if (currentTask) {
            try {
                this.taskManager.incrementTaskPomodoros(currentTask.id);
                this.updateTasksDisplay();
            } catch (error) {
                console.error('Error recording task pomodoro:', error);
            }
        }
    }
    
    /**
     * HTML转义
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 全局应用实例
let pomodoroApp;

// DOM加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM loaded, initializing app...');
    pomodoroApp = new PomodoroApp();
    pomodoroApp.init();
});

// 导出到全局作用域（用于调试）
window.pomodoroApp = pomodoroApp;